import {Component, ElementRef, Input, ViewChild} from "@angular/core";
import {FavoriteGroup, UserGroup} from "@shared/models/UserInfo";
import {FlatTreeControl} from "@angular/cdk/tree";
import {NzTreeFlatDataSource, NzTreeFlattener} from "ng-zorro-antd/tree-view";
import {NzModalService} from "ng-zorro-antd/modal";
import {NzContextMenuService, NzDropdownMenuComponent} from "ng-zorro-antd/dropdown";
import {InputDialogContent} from "@/app/pages/common/input-dialog-content";
import {SearchUserCard} from "@/app/pages/user/setting/search-user/search-user-card";
import {UserActionService, UserGroupActionReq} from "@core/service/UserActionService";
import {NzMessageService} from "ng-zorro-antd/message";
import {BBYUtils} from "@shared/utils/BBYUtils";

interface FlatNode {
  expandable: boolean;
  id:string
  name: string;
  level: number;
  disabled: boolean
  content?:UserGroupNode[]
}


interface UserGroupNode {
  id: string
  name: string
  content?: UserGroupNode[]
}

@Component({
  selector: 'bby-user-group-card',
  templateUrl:'./user-group-card.html'
})
export class UserGroupCard {
  @Input()
  name: string = ''
  loading=true;
  error: { code:string,msg:string }|undefined;

  idParentMap=new Map<string,string>()
  treeData: UserGroupNode[] = [
    {
      id: '',
      name: '默认分组',
      content: []
    }
  ];
  private transformer = (node: UserGroupNode, level: number): FlatNode => ({
    expandable: !!node.content,
    name: node.name,
    level,
    disabled: false,
    id: node.id,
    content:node.content
  });

  treeControl = new FlatTreeControl<FlatNode>(
    node => node.level,
    node => node.expandable
  );

  treeFlattener = new NzTreeFlattener(
    this.transformer,
    node => node.level,
    node => node.expandable,
    node => node.content
  );

  dataSource = new NzTreeFlatDataSource(this.treeControl, this.treeFlattener);
  // 右键菜单操作对象
  selectedNode: FlatNode | undefined

  constructor(
    private dialogService: NzModalService,
    private nzContextMenuService: NzContextMenuService,
    private userActionService:UserActionService,
    private message: NzMessageService
  ) {
    this.flash();
    // this.dataSource.setData(this.treeData);
  }

  setData(data:UserGroupNode[]){
    this.idParentMap.clear();
    for (let group of data){
      if (group.content&&group.content.length>0){
        for(let user of group.content){
          this.idParentMap.set(user.id,group.id)
        }
      }
    }
    this.dataSource.setData(data)
  }
  flash() {
    this.loading=true;
    BBYUtils.handelResult(
      this.userActionService.getUserGroups(),
      res => {
        console.log(res)
        this.setData(res.data)
        this.loading=false;
        this.error=undefined;
      },
      res => {
        this.loading=false;
        this.message.error(res.msg)
        this.error={
          code:res.code+'',
          msg:res.msg
        }
      });
  }

  hasChild = (_: number, node: FlatNode): boolean => node.expandable;

  openClick() {
    if (!this.selectedNode) {
      return
    }
    if (this.selectedNode.expandable) {
      this.treeControl.expand(this.selectedNode)
    }
  }

  rightClickFile($event: MouseEvent, rightClickMenu: NzDropdownMenuComponent, node: FlatNode) {
    this.selectedNode = node;
    console.log(node)
    this.nzContextMenuService.create($event, rightClickMenu);
  }

  deleteClick() {
    if (!this.selectedNode) {
      return
    }
    let node = this.selectedNode;
    this.dialogService.warning({
      nzTitle: '删除',
      nzWidth: '400px', nzCentered: true,
      nzCancelText: '取消',
      nzContent: node.expandable? `确认要删除分组 [${node.name}]？`:`确认要删除这个用户？ [${node.name}]`,
      nzOnOk: ($event: Event) => {
        let option:UserGroupActionReq;
        if(node.expandable) {
          option = {
            opera:'deleteGroup',
            groupId:node.id
          }
        }else {
          option={
            opera:'deleteUser',
            groupId:this.idParentMap.get(node.id),
            userId:node.id
          }
        }
        this.setUserGroups(option)
      }
    })
  }

  renameClick() {
    if (!this.selectedNode) {
      return;
    }
    let node = this.selectedNode;
    this.dialogService.create({
      nzTitle: '重命名', nzWidth: '400px',
      nzContent: InputDialogContent,
      nzComponentParams: {
        value: node.name
      },
      nzOnOk: (page) => {
        if(!node.expandable){
          return;
        }
        let option:UserGroupActionReq = {
          opera:'renameGroup',
          groupId:node.id,
          newName:page.value
        }
        this.setUserGroups(option)
      }
    })
  }

  addGroupClick() {
    this.dialogService.create({
      nzTitle: '新建分组', nzWidth: '400px',
      nzContent: InputDialogContent,
      nzComponentParams: {
        placeholder:'请输入新建用户组名'
      },
      nzOnOk: (page) => {
        let option:UserGroupActionReq = {
          opera:'addGroup',
          newName:page.value
        }
        this.setUserGroups(option)
      }
    })
  }
  setUserGroups(data:UserGroupActionReq) {
    console.log(data)
    this.loading=true;
    BBYUtils.handelResult(
      this.userActionService.setUserGroups(data),
      res => {
        // this.flash();
        this.setData(res.data)
        this.loading=false;
      },res => {
        this.loading=false;
        this.message.error(res.msg)
      })
  }

  addUserClick() {
    if (!this.selectedNode||!this.selectedNode.expandable||!this.selectedNode.id){
      return
    }
    let contentIdSet = new Set<string>()
    this.selectedNode.content?.forEach(user=>{
      contentIdSet.add(user.id)
    })
    console.log(this.selectedNode)
    console.log(contentIdSet)
    this.dialogService.create({
      nzTitle: '添加用户', nzWidth: '400px',
      nzContent: SearchUserCard,
      nzCancelText:null,
      nzOkText:'完成',
      nzComponentParams: {
        contentIdSet,
        groupId:this.selectedNode.id
      },
      nzOnOk: (page) => {
        this.flash();
      }
    })
  }
}
